package m202401.d17;

import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/1/17 15:14
 */
//02. 二叉树的层序遍历
public class Q02 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return new LinkedList<>();
        }
        List<List<Integer>> rs = new LinkedList<>();
        LinkedList<TreeNode> list = new LinkedList<>();
        list.addLast(root);
        list.addLast(null);
        List<Integer> line = new LinkedList<>();
        while (!list.isEmpty()) {
            TreeNode node = list.removeFirst();
            if (node == null) {
                rs.add(line);
                line = new LinkedList<>();
                if (!list.isEmpty()) {
                    list.addLast(null);
                }
                continue;
            }
            line.add(node.val);
            if (node.left != null) {
                list.addLast(node.left);
            }
            if (node.right != null) {
                list.addLast(node.right);
            }
        }
        return rs;
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
